<?php
include('../resource/db/db.php');
$pageTitle = "卡片详情";
$currentPage = "detail";

// 检查用户是否已登录
if (!isset($_COOKIE['user_id'])) {
    header("Location: ../main/login.php");
    exit();
}

// 检查卡片ID和卡组ID是否存在
if (!isset($_GET['card_id']) || !isset($_GET['set_id'])) {
    header("Location: ../main/user-index.php");
    exit();
}

$card_id = $_GET['card_id'];
$set_id = $_GET['set_id'];

// 获取卡片详情
$sql = "SELECT * FROM cards WHERE card_id='$card_id' AND set_id='$set_id' AND is_deleted=FALSE";
$result = $conn->query($sql);
$row = $result->fetch_assoc();

// 获取用户的卡组及其卡片数量和创建时间
$user_id = $_COOKIE['user_id'];
$sets_sql = "SELECT s.set_id, s.name, s.created_at, COUNT(c.card_id) AS card_count 
             FROM sets s
             LEFT JOIN cards c ON s.set_id = c.set_id
             WHERE s.user_id='$user_id' AND s.is_deleted=FALSE
             GROUP BY s.set_id";
$sets_result = $conn->query($sets_sql);

// 处理删除请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
    $delete_card_id = $_POST['card_id'];
    $delete_sql = "UPDATE cards SET is_deleted=TRUE WHERE card_id=?";
    $delete_stmt = $conn->prepare($delete_sql);
    $delete_stmt->bind_param('i', $delete_card_id);
    if ($delete_stmt->execute()) {
        Header("Location: ../learn/set.php?set_id=$set_id");
        exit();
    } else {
        echo "<p>删除卡片失败，请重试。</p>";
    }
    $delete_stmt->close();
}

// 处理修改请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['delete'])) {
    $title = $_POST['title'];
    $content = $_POST['content'];

    // 处理正面图片上传
    if (isset($_FILES['images1'])) {
        $imageDir = '../uploads/';
        foreach ($_FILES['images1']['tmp_name'] as $index => $tmpName) {
            if ($_FILES['images1']['error'][$index] === UPLOAD_ERR_OK) {
                $imagePath = $imageDir . basename($_FILES['images1']['name'][$index]);
                if (move_uploaded_file($tmpName, $imagePath)) {
                    $title .= '<img src="' . $imagePath . '" style="max-width: 1000px; max-height: 100px;">';
                }
            }
        }
    }

    // 处理反面图片上传
    if (isset($_FILES['images2'])) {
        $imageDir = '../uploads/';
        foreach ($_FILES['images2']['tmp_name'] as $index => $tmpName) {
            if ($_FILES['images2']['error'][$index] === UPLOAD_ERR_OK) {
                $imagePath = $imageDir . basename($_FILES['images2']['name'][$index]);
                if (move_uploaded_file($tmpName, $imagePath)) {
                    $content .= '<img src="' . $imagePath . '" style="max-width: 1000px; max-height: 100px;">';
                }
            }
        }
    }

    // 更新卡片信息到数据库
    $stmt = $conn->prepare("UPDATE cards SET title=?, content=?, updated_at=NOW() WHERE card_id=? AND is_deleted=FALSE");
    $stmt->bind_param('ssi', $title, $content, $card_id);
    if ($stmt->execute()) {
        echo "<p>卡片更新成功！</p>";
        Header("Location: ../learn/set.php?set_id=$set_id");
    } else {
        echo "<p>卡片更新失败，请重试。</p>";
    }
    $stmt->close();
}
?>

<!DOCTYPE html>
<html>

<head>
    <title>卡片详情</title>
    <link rel="stylesheet" href="../resource/css/styles.css">
</head>

<body>
    <?php include('../resource/navbar.php'); ?>
    <div class="container">
        <h2>卡片详情</h2>
        <!-- 删除卡片 -->
        
        <div class="container">
            <?php
            if ($row) {
                echo "<div class='card-container'>";
                echo "<a href='../learn/set.php?set_id=" . $set_id . "'>返回卡组</a>";
                echo "<div class='front'>";
                echo "<h2>正面</h2>";
                echo $row['title'];
                echo "</div>";

                echo "<div class='back' style='padding-top:20px; padding-bottom:20px'>";
                echo "<h2>反面</h2>";
                echo $row['content'];
                echo "</div>";
                echo "</div>";

                echo "<p>创建时间: " . $row['created_at'] . "</p>";
                echo "<p>更新时间: " . $row['updated_at'] . "</p>";
            } else {
                echo "<p>卡片不存在或已被删除。</p>";
                Header("Location: ../learn/set.php?set_id=$set_id");
            }
            ?>
            <form method="post" action="">
            <input type="hidden" name="card_id" value="<?php echo $card_id; ?>">
            <button type="submit" name="delete" class="btn btn-danger">删除卡片</button>
        </form>
        </div>
        <h2>修改卡片</h2>
        <div class="upload-card">
            <form method="post" action="" enctype="multipart/form-data">
                <div class="form-group title">
                    <label for="title">正面（标题）:</label>
                    <?php
                    // 去除img
                    $title = preg_replace('/<img[^>]+>/', '', $row['title']);
                    $content = preg_replace('/<img[^>]+>/', '', $row['content']);
                    ?>
                    <textarea id="title" name="title" class="form-control" required><?php echo "$title" ?></textarea>
                    <label for="images1">正面图片:</label>
                    <input type="file" id="images1" name="images1[]" class="form-control" accept="image/*" multiple>
                </div>
                <div class="form-group content">
                    <label for="content">反面（内容）:</label>
                    <textarea id="content" name="content" class="form-control" required><?php echo "$content" ?></textarea>
                    <label for="images2">反面图片:</label>
                    <input type="file" id="images2" name="images2[]" class="form-control" accept="image/*" multiple>
                </div>
                <div class="form-group">
                    <label for="set_id">选择卡组:</label>
                    <select id="set_id" name="set_id" class="form-control" required>
                        <?php
                        if ($sets_result->num_rows > 0) {
                            while ($set_row = $sets_result->fetch_assoc()) {
                                echo "<option value='" . $set_row['set_id'] . "'>" . $set_row['name'] . " - " . $set_row['card_count'] . " 张卡片 - 创建时间: " . $set_row['created_at'] . "</option>";
                            }
                        } else {
                            echo "<option value='' disabled>暂无卡组</option>";
                        }
                        ?>
                    </select>
                </div>
                <button type='submit'>保存更改</button>
            </form>
        </div>

        <h2>新建卡组</h2>
        <div class="upload-set">
            <div class="form-group">
                <label for="new_set">卡组名称:</label>
                <input type="text" id="new_set" name="new_set" class="form-control">
                <label for="new_set_info">卡组简介:</label>
                <input type="text" id="new_set_info" name="new_set_info" class="form-control">
                <div class="btn">
                    <button type="button" id="create_set" class="btn btn-primary">确认</button>
                </div>
            </div>
        </div>
    </div>

</body>

</html>
